<?php

namespace App\Http\Resources\CruiseCheck;

use App\Http\Resources\BaseResource;
use App\Http\Resources\Cruise\CruiseTemplateResource;
use App\Models\Cruise\CruiseCheckSelfTaskCompanyMappingModel;
use App\Models\Cruise\CruiseCheckSelfTaskModel;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\MissingValue;

class CruiseCheckSelfTaskResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            "id"                 => $this->id,
            "name"               => $this->name,
            "rule"               => $this->rule,
            "ruleText"           => translateEnumCodeToCn(CruiseCheckSelfTaskModel::RULE_TEXT, $this->rule),
            "taskStartTime"      => formatDateWithRule($this->taskStartTime, "Y-m-d"),
            "taskEndTime"        => formatDateWithRule($this->taskEndTime, "Y-m-d"),
            "executeType"        => $this->executeType,
            "executeTypeText"    => CruiseCheckSelfTaskModel::EXECUTE_TYPE_TEXT[$this->executeType] ?? "",
            "executeStartHis"    => $this->executeStartHis,
            "executeEndHis"      => $this->executeEndHis,
            "executeStartBefore" => $this->executeStartBefore,
            "executeEndAfter"    => $this->executeEndAfter,
            "templateId"         => $this->templateId,
            "templateDetail"     =>
                $this->whenLoaded(
                    "cruiseTemplateRel",
                    function () {
                        return CruiseTemplateResource::collection([$this->cruiseTemplateRel])->getIterator()->current();
                    },
                    new MissingValue()
                ),
            "status"             => $this->status,
            "statusText"         => translateEnumCodeToCn(CruiseCheckSelfTaskModel::STATUS_TEXT, $this->status),
            "updatedAt"          => formatDate($this->updatedAt->timestamp),
            "checkCompany"       =>
                $this->whenLoaded(
                    "cruiseCheckSelfTaskCompanyMappingsRel",
                    function () {
                        return $this->cruiseCheckSelfTaskCompanyMappingsRel->map(function (
                            CruiseCheckSelfTaskCompanyMappingModel $checkSelfTaskCompanyMappingModel
                        ) {
                            return [
                                "name" => object_get($checkSelfTaskCompanyMappingModel,
                                    "cruiseCheckCompanyRel.fsCompanyRel.name", "-"),
                                "id"   => object_get($checkSelfTaskCompanyMappingModel, "cruiseCheckCompanyRel.id", 0),
                            ];
                        })->values();
                    },
                    new MissingValue()
                )
        ];
    }

}
